package com.learn.disruptor.consumer;

import cn.hutool.core.util.StrUtil;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.UtilityClass;

import java.util.concurrent.CountDownLatch;

/**
 * @author XuYang
 * @since 2025/2/21 17:56
 */
@UtilityClass
public class SimpleConsumer {

    public Disruptor<Event> start(int ringBufferSize, EventConsumer... consumers) {
        Disruptor<Event> disruptor = new Disruptor<>(Event::new, ringBufferSize, DaemonThreadFactory.INSTANCE);

        disruptor.handleEventsWith(consumers);
        disruptor.after(consumers);
        disruptor.start();
        return disruptor;
    }


    @Data
    public static class Event {
        private Long id;
    }

    @AllArgsConstructor(staticName = "of")
    @Data
    public class EventConsumer
        implements EventHandler<Event>
    {
        private String name;
        private CountDownLatch latch;

        @Override
        public void onEvent(Event event, long sequence, boolean endOfBatch) throws Exception {
            System.out.println(name + ": " + StrUtil.join(" -> ", Thread.currentThread().getName(), event.getId(), sequence, endOfBatch));
            latch.countDown();
        }
    }
}
